const express = require('express');
const fs = require('fs');
const path = require('path');
const sharp = require('sharp');

var router = express.Router();
const IMAGES_DIR = path.join(process.cwd(), 'public', 'images');
const THUMBNAILS_DIR = path.join(process.cwd(), 'public', 'thumbnails');

if (!fs.existsSync(THUMBNAILS_DIR)) {
    fs.mkdirSync(THUMBNAILS_DIR, { recursive: true });
}

// 生成缩略图（可选：预生成或按需生成）
async function generateThumbnail(imagePath) {
    const thumbnailPath = imagePath.replace(IMAGES_DIR, THUMBNAILS_DIR).replace(/\.[^/.]+$/, '.jpg');
    const dirPath = path.dirname(thumbnailPath)
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
        console.log(`Directory created: ${dirPath}`);
    }
    if (!fs.existsSync(thumbnailPath)) {
        await sharp(imagePath)
            .resize(150, 150, { fit: 'inside' })
            .toFile(thumbnailPath);
    }
    return thumbnailPath.replace(THUMBNAILS_DIR, '').replace(/^\//, '');
}
// 递归读取目录（包含子目录）
function readDirectoryRecursive(dirPath) {
    const items = fs.readdirSync(dirPath, { withFileTypes: true });
    let result = [];
    
    items.forEach(item => {
        const fullPath = path.join(dirPath, item.name);
        if (item.isDirectory()) {
            // 递归读取子目录
            //result = result.concat(readDirectoryRecursive(fullPath));
        } else if (/\.(jpg|jpeg|png|gif)$/i.test(item.name)) {
            // 只包含图片文件
            result.push({
                name: item.name,
                path: fullPath,
                // 转换为相对于public/images的路径
                relativePath: fullPath.replace(IMAGES_DIR, '').replace(/^\//, '')
            });
        }
    });
    
    return result;
}

// 获取图片列表（支持分页和目录筛选）
router.get('/list', async (req, res) => {
    try {
        const { dir = '', page = 1, limit = 9 } = req.query;
        const currentDir = path.join(IMAGES_DIR, dir);
        
        // 递归获取当前目录及子目录的所有图片
        const allImages = readDirectoryRecursive(currentDir);
        
         // Async loop allImages and generate thumbnail for each image
        for (const img of allImages) {
            img.thumbnail = await generateThumbnail(img.path);
        }
        
        const total = allImages.length;
        const totalPages = Math.ceil(total / limit);
        
        // 分页处理
        const paginatedImages = allImages
            .sort((a, b) => a.name.localeCompare(b.name)) // 按文件名排序
            .slice((page - 1) * limit, page * limit)
            .map(img => ({
                ...img,
                // 转换为前端可访问的URL
                thumbnail: `/public/thumbnails/${img.thumbnail}`,
                original: `/public/images/${img.relativePath}`
            }));
        
        res.json({
            dir,
            page,
            limit,
            total,
            totalPages,
            images: paginatedImages,
            // 返回子目录列表（用于前端导航）
            subDirectories: getSubDirectories(IMAGES_DIR, dir)
        });
    } catch (err) {
        console.error(err);
        res.status(500).send('服务器错误');
    }
});

// 获取指定目录的子目录列表
function getSubDirectories(baseDir, currentDir) {
    const relativePath = currentDir.replace(baseDir, '').replace(/^\//, '');
    const currentFullPath = path.join(baseDir, relativePath);
    
    try {
        const items = fs.readdirSync(currentFullPath, { withFileTypes: true });
        return items
            .filter(item => item.isDirectory())
            .map(item => ({
                name: item.name,
                path: path.join(relativePath, item.name).replace(/^\//, '')
            }));
    } catch (err) {
        return [];
    }
}

/* GET image page. */
router.get('/', async (_req, res) => {;
  res.render('image-list', { title: 'Image Gallery' });
});

// 静态文件服务
module.exports = router;

